package com.nit.lab.utils;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * @ClassName：UploadFileUtil
 * @Author: wangSheng
 * @Date: 2020/7/22
 */
public class UploadFileUtil {

    private static Random random = new Random();

    /**
     * 根据源文件的名字获取类型，与当前的时间进行拼接,顺便插入随机数进行大程度排重
     * 返回新的名字
     */
    private static String getTempFileName(String oldFileName) {
        StringBuilder stringBuilder = new StringBuilder();
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String[] fileNames = oldFileName.split("\\.");
        return stringBuilder.append(fileName).append(random.nextInt(1000)).append(".").append(fileNames[1]).toString();
    }

    public static String uploadFile(File file) {
        return uploadFile(file, "../upload", getTempFileName(file.getName()));
    }

    public static String uploadFile(File file, String path) {
        return uploadFile(file, path, getTempFileName(file.getName()));
    }

    public static String uploadFile(File file, String path, String fileName) {
        File tempFile = new File(path);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        try (
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                FileOutputStream fos = new FileOutputStream(path + "\\" + fileName);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
        ) {
            int size;
            byte[] buf = new byte[1024];
            while ((size = bis.read(buf)) != -1) {
                bos.write(buf, 0, size);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path + "/" + fileName;
    }

//    public static void main(String[] args) {
//        uploadFile(new File("C:\\Users\\wangsheng\\Desktop\\123.txt"));
//    }
}
